﻿using Volo.Abp.Application;
using Volo.Abp.Modularity;
using Volo.Abp.Authorization;
using EcoSystem.WebApi;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Collections.Generic;
using System;
using System.Reflection;

namespace EcoSystem;
[DependsOn(
typeof(EcoSystemDomainSharedModule),
typeof(AbpDddApplicationContractsModule),
    typeof(AbpAuthorizationModule)
    )]
public class EcoSystemApplicationContractsModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        this.AddHttpApiServices(context);
        base.ConfigureServices(context);
    }

    /// <summary>
    /// 添加HTTP调用服务 参考资料
    /// https://webapiclient.github.io/guide/getting-started.html
    /// </summary>
    /// <param name="context"></param>
    private void AddHttpApiServices(ServiceConfigurationContext context)
    {
        var configuration = context.Services.GetConfiguration();

        context.Services.AddTransient<HttpApiRequestHandler>();

        //获取所有远程调用接口
        var types = this.GetType().Assembly.GetTypes().Where(
            x => x.IsInterface && x.IsAssignableTo(typeof(IHttpApi))).ToList();

        //处理其它微服务API接口调用
        var hosts = new Dictionary<string, Uri>();
        types.ForEach(type =>
        {
            var attribute = type.GetCustomAttribute<HttpApiServiceAttribute>();
            var serviceName = attribute?.ServceName ?? "Default";
            var host = hosts.GetOrAdd(serviceName, () =>
            {
                var url = configuration[$"RemoteServices:{serviceName}:BaseUrl"];
                url = url.RemovePostFix("/") + "/";
                return new Uri(url);
            });
            context.Services.AddHttpApi(type, o =>
            {
                o.HttpHost = host;
            }).AddHttpMessageHandler(() =>
            {
                return context.Services.GetServiceLazy<HttpApiRequestHandler>().Value;
            });
        });
    }

}
